import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collection;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

public class Ready extends HttpServlet {

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		ArrayList<Game> games = GamesHandler.games;

		Game currentGame = null;
		ArrayList<Ship> playersShipArray = new ArrayList<Ship>();
		String comand = request.getParameter("alliedShips");

		Gson gson = new Gson();
		Type shipType = new TypeToken<ArrayList<Ship>>() {
		}.getType();
		playersShipArray = gson.fromJson(comand, shipType);

		HttpSession session = request.getSession();
		String name = "";
		int id=-1;
		try{
			name = session.getAttribute("username").toString();
			id = (Integer) session.getAttribute("gameID");
			
			for (int i = 0; i < games.size(); i++) {
				if (games.get(i).getId() == id) {

					currentGame = games.get(i);
					if (currentGame.getPl1().equals(name)) {
						// add player1(who created game) ships to the game
						currentGame.setPl1Ships(playersShipArray);
						currentGame.setPl1IsReady(true);
						break;
					}
					if (currentGame.getPl2().equals(name)) {
						// add player2 ships to the game
						currentGame.setPl2Ships(playersShipArray);
						currentGame.setPl2IsReady(true);
						break;
					}

				}

			}

			response.setContentType("application/json");
			PrintWriter out = response.getWriter();

			if (currentGame.isPl1IsReady() && currentGame.isPl2IsReady()) {
				out.print("joined");
				out.flush();

			} else {
				out.print("wait");
				out.flush();
			}
			out.close();
		}catch (NullPointerException e) {
			PrintWriter out = response.getWriter();
			out.print("error");
			out.flush();
			try {
				finalize();
			} catch (Throwable e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		}


	}

}
